const Router = require("koa-router");
const loginRouter = new Router();
const { getToken } = require("../../../../middleware/token");

const UserModel = require("../../../../sql/userInfo");
const { successMessage, errorMessage } = require("../../../../util/send");

//用户登录
loginRouter.post("/login", async (ctx, next) => {
  try {
    const { userName, password } = ctx.request.body; //获取用户名密码
    const userIsHave = await UserModel.getUserName(userName);
    if (!userIsHave.length) {
      ctx.body = new errorMessage(null, "当前登录用户不存在！");
      return;
    } else {
      let userInfo = userIsHave[0];
      if (password == userInfo.password) {
        ctx.body = new successMessage(
          { token: getToken({ user: userName, password: password }) },
          `${userInfo.userInfo}登陆成功！`
        );
      } else {
        ctx.body = new errorMessage(null, "密码错误！");
      }
    }
  } catch (error) {
    ctx.app.emit("error", error);
    ctx.body = new errorMessage(null, error.message);
  }
});

module.exports = {
  loginRouter,
};
